#!/bin/sh

APP=antares

# CREATE THE FOLDER
mkdir /opt/$APP
cd /opt/$APP

# ADD THE REMOVER
echo '#!/bin/sh' >> /opt/$APP/remove
echo "rm -R -f /usr/local/share/applications/AM-$APP.desktop /opt/$APP /usr/local/bin/$APP" >> /opt/$APP/remove
chmod a+x /opt/$APP/remove

# DOWNLOAD THE APPIMAGE
mkdir tmp
cd ./tmp

wget https://github.com/$(wget https://github.com/Fabio286/antares/releases/latest | grep -E '/.*/.*/.*arm64.AppImage' -o);

version=$(ls /opt/$APP/tmp)
echo "$version" >> /opt/$APP/version

cd ..
mv ./tmp/*mage ./$APP
chmod a+x /opt/$APP/$APP
rmdir ./tmp

# LINK
ln -s /opt/$APP/$APP /usr/local/bin/$APP

# SCRIPT TO UPDATE THE PROGRAM
echo '#!/bin/sh' >> /opt/$APP/AM-updater
echo "APP=$APP" >> /opt/$APP/AM-updater
echo 'version0=$(cat /opt/$APP/version)

url=https://github.com/Fabio286/antares/releases/latest' >> /opt/$APP/AM-updater

echo 'if curl -L -s $url | grep -ioF "$version0"; then' >> /opt/$APP/AM-updater
echo '  echo "Update not needed!".'  >> /opt/$APP/AM-updater
echo 'else' >> /opt/$APP/AM-updater
echo "  notify-send 'A new version of $APP is available, please wait'" >> /opt/$APP/AM-updater
echo "  mkdir /opt/$APP/tmp
  cd /opt/$APP/tmp" >> /opt/$APP/AM-updater

########################################################################################

function1='$(wget https://github.com/Fabio286/antares/releases/latest -O -'
function2="grep -E '/.*/.*/.*arm64.AppImage' -o)"
function3='$(ls /opt/$APP/tmp)'

echo "  wget https://github.com/$function1 | $function2
  version=$function3" >> /opt/$APP/AM-updater

########################################################################################

echo '  cd ..
  if test -f ./tmp/*mage; then rm ./version
  fi
  echo "$version" >> ./version' >> /opt/$APP/AM-updater
echo "  mv ./tmp/*mage ./$APP
  chmod a+x /opt/$APP/$APP
  rmdir ./tmp
fi" >> /opt/$APP/AM-updater
chmod a+x /opt/$APP/AM-updater

# LAUNCHER
rm -f /usr/local/share/applications/AM-$APP.desktop
echo "[Desktop Entry]
Name=Antares
Exec=antares --no-sandbox %U
Terminal=false
Type=Application
Icon=/opt/$APP/$APP.svg
StartupWMClass=Antares
Comment=A cross-platform easy to use SQL client.
Categories=Development;" >> /usr/local/share/applications/AM-$APP.desktop

# ICON
wget https://raw.githubusercontent.com/ivan-hc/AM-application-manager/main/programs/.icons/$APP/$APP.svg
